<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="800px"
    append-to-body
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <!-- 预览区域 -->
        <el-col :span="12">
          <LinkCardPreview :form-data="formData" />
        </el-col>
        
        <!-- 表单区域 -->
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="formData.title"
              placeholder="请输入标题"
              maxlength="10"
              show-word-limit
            />
          </el-form-item>
          
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              placeholder="请输入描述"
              maxlength="50"
              show-word-limit
              :rows="3"
            />
          </el-form-item>
          <el-form-item label="图标" prop="icon">
            <UploadImg v-model="formData.icon" />
          </el-form-item>
          <el-form-item label="企微链接" prop="url">
            <el-input
              v-model="formData.url"
              placeholder="请输入企微链接"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { LinkCardApi, LinkCardVO } from '@/api/system/linkcard'
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import LinkCardPreview from './LinkCardPreview.vue'

/** 短链卡片 表单 */
defineOptions({ name: 'LinkCardForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const visible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  title: undefined,
  description: undefined,
  icon: undefined,
  url: undefined,
})
const formRules = reactive({
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' },
    { max: 10, message: '标题长度不能超过10个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '描述不能为空', trigger: 'blur' },
    { max: 50, message: '描述长度不能超过50个字符', trigger: 'blur' }
  ],
  url: [{ required: true, message: '企微链接不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  visible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await LinkCardApi.getLinkCard(id)
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as LinkCardVO
    if (formType.value === 'create') {
      await LinkCardApi.createLinkCard(data)
      message.success(t('common.createSuccess'))
    } else {
      await LinkCardApi.updateLinkCard(data)
      message.success(t('common.updateSuccess'))
    }
    visible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    title: undefined,
    description: undefined,
    icon: undefined,
    url: undefined,
  }
  formRef.value?.resetFields()
}

const cancel = () => {
  visible.value = false
}
</script>

<style scoped>
.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
</style>
